import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from '@/utils/storage'

// 一级路由
import LayoutIndex from '@/views/LayoutIndex'
import HomeIndex from '@/views/HomeIndex'
import NewsIndex from '@/views/NewsIndex'
import SearchIndex from '@/views/SearchIndex'
import UserIndex from '@/views/UserIndex'
import LoginIndex from '@/views/LoginIndex'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: LoginIndex
  },
  {
    path: '/',
    component: LayoutIndex,
    redirect: '/home',
    children: [
      {
        path: '/home',
        component: HomeIndex
      },
      {
        path: '/search',
        component: SearchIndex
      },
      {
        path: '/news',
        component: NewsIndex
      },
      {
        path: '/user',
        component: UserIndex
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

const whiteList = ['/login']

router.beforeEach((to, from, next) => {
  const token = getToken()
  if (token) {
    next()
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('login')
    }
  }
})

export default router